<?php
namespace app\mini\controller\v1\client;
use app\common\exception\UploadException;
use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\library\Upload;
use app\common\logic\CarLogic;
use app\common\logic\MaintainLogic;
use app\common\logic\MoneyRecordLogic;
use app\common\model\CarBrands;
use app\common\model\CarImages;
use app\common\model\CarSeries;
use app\mini\controller\Common;
use \app\common\model\Car as carModel;
use app\mini\controller\v1\client\validate\carValidate;
use think\Config;
use think\Db;
use think\Env;
use think\Exception;
use think\Request;
use think\response\Json;

class Car extends Common
{

    public $CarLogic;
    public $MaintainLogic;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->CarLogic = new CarLogic();
        $this->MaintainLogic = new MaintainLogic();
    }

    /**
     * 我的车库
     * @return array
     */
    public function index():Json
    {
        $res = $this->exception(function () {
            return $this->CarLogic->index();
        });
        return $this->response($res);
    }

    /**
     * 新增车辆
     * @return array
     */
    public function add():Json
    {
        $res = $this->exception(function () {
            return $this->CarLogic->add(request()->param());
        });
        return $this->response($res);
    }

    /**
     * 更新车辆
     * @return array
     */
    public function edit():Json
    {
        $res = $this->exception(function () {
            return $this->CarLogic->edit(request()->param());
        });
        return $this->response($res);
    }

    /**
     * VIN码
     * @return array
     */
    public function ocr():Json
    {
        $res = $this->exception(function () {
            $file = $this->request->file('file');
            $res = file_get_contents($file->getInfo()['tmp_name']);
            $client = new \AipOcr(Env::get('baidu.appId'),Env::get('baidu.apiKey'),Env::get('baidu.secretKey'));
            $info = $client->vinCode($res);
            if (isset($info['words_result']))
                return $info['words_result'][0]['words'];
            throw new ApiException('系统错误',404);
        });
        return $this->response($res);
    }



    /**
     * 车辆删除
     * @return array
     */
    public function del()
    {
        Db::startTrans();
        try{
            $car_id = input('id',0);
            if (empty($car_id)){
                self::$http_code = 200;
                throw new Exception("车辆ID参数缺失");
            }
            $data = carModel::get(['member_id'=>$this->member_info_arr['member_id'],'id'=>$car_id]);
            if (empty($data)){
                self::$http_code = 200;
                throw new Exception("车辆信息不存在");
            }
            if ($data['is_default'] == 1){//转移默认设置
               $car_info = carModel::get(['member_id'=>$this->member_info_arr['member_id'],'is_del'=>0,'is_default'=>0]);
               if ($car_info)
                   carModel::update(['is_default'=>1],['id'=>$car_info['id']]);
            }
            carModel::update(['is_del'=>1,'is_default'=>0],['id'=>$car_id]);
            Db::commit();
            return show(200, 'success');
        }catch (Exception $e){
            Db::rollback();

            return show(self::$err_code, $e->getMessage(), [], self::$http_code);
        }
    }

    /**
     * 设为默认
     * @return array
     */
    public function set_default()
    {
        Db::startTrans();
        try{
            $car_id = input('id',0);
            if (empty($car_id)){
                self::$http_code = 200;
                throw new Exception("车辆ID参数缺失");
            }
            $car_info = carModel::get($car_id);
            if (empty($car_info)){
                self::$http_code = 200;
                throw new Exception("车辆信息不存在");
            }
            carModel::update(['is_default'=>0],['member_id'=>$this->member_info_arr['member_id'],'is_default'=>1]);
            $res = carModel::update(['is_default'=>1],['member_id'=>$this->member_info_arr['member_id'],'id'=>$car_id]);
            if ($res === false){
                self::$http_code = 200;
                throw new Exception("设置失败");
            }
            Db::commit();
            return show(200, 'success');
        }catch (Exception $e){
            Db::rollback();
            return show(self::$err_code, $e->getMessage(), [], self::$http_code);
        }
    }

    /**
     * 更多信息
     */
    public function more_info()
    {

        $res = $this->exception(function () {
            return $this->CarLogic->moreInfo(request()->param());
        });
        return $this->response($res);

    }


    public function update_picture()
    {
        $res = $this->exception(function () {
            return $this->CarLogic->update_picture(request()->param());
        });
        return $this->response($res);
    }


    /**
     * 我的车辆信息
     * @return Json
     */
    public function info():Json
    {
        $res = $this->exception(function () {
            return $this->CarLogic->info(request()->param());
        });
        return $this->response($res);
    }


    /**
     * 我的车辆信息更新
     * @return Json
     */
    public function update():Json
    {
        $res = $this->exception(function () {
            return $this->CarLogic->updates(request()->param());
        });
        return $this->response($res);
    }


    /**
     * 保养记录
     * @return Json
     */
    public function maintain():Json
    {
        $res = $this->exception(function () {
            $params = request()->param();
            $params['member_id'] = MemberVo::instance()->getMemberId();
            return $this->MaintainLogic->index($params);
        });
        return $this->response($res);
    }






    /**
     * 车辆详情图片上传
     * @return array
     */
    public function upload(){
        $file = request()->file('image');
        $type = input('type','');
        $car_id = input('id','');
        try {
            if (empty($type) || empty($car_id)){
                self::$http_code = 400;
                throw new Exception('参数缺失');
            }
            Config::set('upload.cdnurl', '');
            $upload = new Upload($file);
            $file_name = md5($car_id . '_' . date('YmdHis') . rand(10000, 99999));
            $attachment = $upload->upload('/uploads/car/'.$file_name);
            $img_info = CarImages::get(['car_id'=>$car_id,'type'=>$type]);
            if ($img_info){
                $attachmentFile = ROOT_PATH . '/public' . $img_info['url'];
                if (is_file($attachmentFile)) {
                    @unlink($attachmentFile);
                }
                CarImages::update(['url'=>$attachment->url],['car_id'=>$car_id,'type'=>$type]);
            }else{
                CarImages::create(['url'=>$attachment->url,'car_id'=>$car_id,'type'=>$type]);
            }
            return show(200, 'success',['url' => Env::get('app.app_host').$attachment->url]);
        } catch(Exception $e) {
            return show(self::$err_code, $e->getMessage(), [], self::$http_code);
        }
    }









}